/*
 * ToolBarConfigReader class includes methods to read
 * xml configuration files
 * THIS IS FOR v1.1
 */
package com.meraklisina.latexeditor;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import org.w3c.dom.*;

import com.meraklisina.latexeditor.mdi.Common.CommonGuiListener;

/**
 * 
 * @author kursattopcu
 */
public class ToolBarConfigReader {

	private String configFilePath;

	public ToolBarConfigReader(String configFilePath) {
		this.configFilePath = configFilePath;
	}

	public String getConfigFilePath() {
		return configFilePath;
	}

	public void setConfigFilePath(String configFilePath) {
		this.configFilePath = configFilePath;
	}

	public String getFullCommandPath() {
		return getConfigFilePath() + "_" + "config";
	}

	public LatexToolBar GenerateButtons(LatexToolBar toolbar) {
		//String executionPath = System.getProperty("user.dir");
		//XmlHandler toolbarConfHandler = new XmlHandler(executionPath+"/"+getConfigFilePath()+"/config.xml");
		XmlHandler toolbarConfHandler = new XmlHandler(getConfigFilePath()+"/config.xml");
		//System.out.println(executionPath+"/"+getConfigFilePath()+"/config.xml");
		System.out.println(getConfigFilePath()+"/config.xml");
		try { // eklendi iptal edilecek TG
			//Belirlenen Toolbar icerisinden Button element lerini oku.TG
			NodeList nodeLst = toolbarConfHandler.GetElementsByTagName("Button");
			for (int s = 0; s < nodeLst.getLength(); s++) {
				Node buttonNode = nodeLst.item(s);
				String name = toolbarConfHandler.GetChildNodeValue(buttonNode, "name");
				String toolTip = toolbarConfHandler.GetChildNodeValue(buttonNode, "tooltip");
				String iconPath = getConfigFilePath() + toolbarConfHandler.GetChildNodeValue(buttonNode, "iconpath");
				String prefix = toolbarConfHandler.GetChildNodeValue(buttonNode, "prefix");
				String suffix = toolbarConfHandler.GetChildNodeValue(buttonNode, "suffix");
				String exampleCommand = toolbarConfHandler.GetChildNodeValue(buttonNode, "exampleCommand");
				final LatexButton button = new LatexButton(name, iconPath, toolTip, prefix, suffix, exampleCommand, getFullCommandPath());

				ActionListener listener = new ActionListener() {

					public void actionPerformed(ActionEvent e) {
						try {
							if (button.getPrefix() != null && button.getPrefix().trim().length() > 0)
								ExeditorLatexEditor.PerformLatexButtonAction(button);
							else
								CommonGuiListener.handleAction(button);
						} catch (Exception e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}

					}
				};
				button.addActionListener(listener);
				toolbar.add(button);
			}
		} catch (Exception e) { // eklendi iptal edilecek TG
			System.out.println("Baslarken alinan hata mesaji:"+e.toString());
			return toolbar;
		}
		return toolbar;
	}
}
